package com.work.controller;

import com.work.bean.Student;
import com.work.bean.Teacher;
import com.work.bean.User;
import com.work.dao.StudentDao;
import com.work.dao.TeacherDao;
import com.work.dao.UserDao;
import com.work.dao.impl.StudentDaoImpl;
import com.work.dao.impl.TeacherDaoImpl;
import com.work.dao.impl.UserDaoImpl;
import com.work.service.StudentService;
import com.work.service.TeacherService;
import com.work.service.UserService;
import com.work.service.impl.StudentServiceImpl;
import com.work.service.impl.TeacherServiceImpl;
import com.work.service.impl.UserServiceImpl;
import com.work.utils.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

public class UserServlet extends BaseServlet{
    private UserService userService = new UserServiceImpl();
    private TeacherDao teacherDao = new TeacherDaoImpl();
    private StudentDao studentDao = new StudentDaoImpl();
    private UserDao userDao = new UserDaoImpl();
    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
            IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        User loginUser = userService.login(new User(username,password));
        if (loginUser == null) {
            req.setAttribute("msg" ,"用户或密码错误！");
            req.setAttribute("username",username);
            req.getRequestDispatcher("/pages/user/login.jsp").forward(req,resp);
        }else {
            String type = loginUser.getType();
            if ("0".equals(type)) {
                int id = loginUser.getId();
                req.getSession().setAttribute("user", loginUser);
                resp.sendRedirect(req.getContextPath()+"/pages/admin/admin.jsp");
            } else if("1".equals(type)) {
                Teacher teacher = teacherDao.queryTeacherByUId(loginUser.getId());
                req.getSession().setAttribute("teacher",teacher);
                req.getSession().setAttribute("user", loginUser);
                resp.sendRedirect(req.getContextPath()+"/MessageServlet?action=queryMessage1");
            }else if("2".equals(type)){
                Student student = studentDao.queryStudentByUId(loginUser.getId());
                req.getSession().setAttribute("student",student);
                req.getSession().setAttribute("user", loginUser);
                System.out.println((Student)req.getSession().getAttribute("student"));
                req.setAttribute("pageNo","1");
                resp.sendRedirect(req.getContextPath()+"/NoticeServlet?action=page&pageNo=1");
//                req.getRequestDispatcher("/pages/student/student.jsp").forward(req, resp);
            }else {
                req.setAttribute("msg" ,"权限错误！");
                req.getRequestDispatcher("/pages/user/login.jsp").forward(req,resp);
            }
        }
    }
    protected void regist(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
            IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String type = req.getParameter("type");
        String rname = req.getParameter("rname");
        String code = req.getParameter("code");
        String token = (String) req.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        req.getSession().removeAttribute(KAPTCHA_SESSION_KEY);
        if(token != null && token.equalsIgnoreCase(code)){
            if(userService.existsUsername(username)){
                System.out.println("用户名[" + username + "]已存在!");
                req.setAttribute("msg","用户名已存在！！");
                req.setAttribute("username", username);
                req.setAttribute("type",type);
                req.setAttribute("rname",rname);
                req.getRequestDispatcher("/pages/user/regist.jsp").forward(req,resp);
            }else {
                userService.registUser(new User(username,password,type,rname));
                req.getRequestDispatcher("/pages/user/login.jsp").forward(req,resp);
            }
        }else {
            req.setAttribute("msg", "验证码错误！！");
            req.setAttribute("username", username);
            req.setAttribute("type",type);
            req.setAttribute("rname",rname);
            System.out.println("验证码[" + code + "]错误");
            req.getRequestDispatcher("/pages/user/regist.jsp").forward(req, resp);
        }
    }

    /**
     * 注销
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
            IOException {
//       1、销毁Session 中用户登录的信息 （或者销毁Session）
        req.getSession().removeAttribute("user");
//       2、重定向到首页 （或登录页面）。
        resp.sendRedirect(req.getContextPath());
    }
    protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
            IOException {
        int id = WebUtils.parseInt(req.getParameter("id"),0);
        userDao.delete(id);
        resp.sendRedirect(req.getContextPath()+"/UserServlet?action=query");
    }
    protected void query(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
            IOException {
        List<User> users = userDao.queryByType("0");
        req.setAttribute("users",users);
        req.getRequestDispatcher("/pages/admin/admin_user/admin_management.jsp").forward(req, resp);
    }
    protected void save(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
            IOException {
        String rname = req.getParameter("rname");
        String username = req.getParameter("username");
        String password = req.getParameter("userpwd1");
        User user = new User(username,password,"0",rname);
        if(userService.existsUsername(username)){
            System.out.println("用户名[" + username + "]已存在!");
            req.setAttribute("msg1","用户名已存在！！");
            req.setAttribute("username1", username);
            req.setAttribute("rname1",rname);
            req.setAttribute("passowrd1",password);
            req.getRequestDispatcher("/pages/admin/admin_user/admin_management_edit.jsp").forward(req,resp);
        }else {
            userService.registUser(user);
            resp.sendRedirect(req.getContextPath()+"/UserServlet?action=query");
        }
    }
    protected void updateAdmin(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
            IOException {
            String password = req.getParameter("password");
            int id = ((User)req.getSession().getAttribute("user")).getId();
            userDao.update(new User(id,null,password,null,null));
            resp.sendRedirect(req.getContextPath()+"/UserServlet?action=query");
    }
}
